from fastapi import APIRouter, Depends, Body, HTTPException
from sqlalchemy.orm import Session
from database import SessionLocal
from crud.record import  get_user_record, update_user_record, delete_user_record, create_user_record
from schemas.record import UserRecordCreate, UserRecordResponse
from crud.page_record import get_all_knowledge_points_by_page, create_knowledge_point ,update_knowledge_point
from models.models import LearnUser
from utils.auth import get_current_user
from schemas.record import PageRecordCreate
from utils.log_manager import app_logger
from datetime import datetime

router = APIRouter(prefix="/record", tags=["Record"])

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.post("/update", response_model=UserRecordResponse)
def update_record(record: UserRecordResponse=Body(...), db: Session = Depends(get_db),current_user: LearnUser = Depends(get_current_user)):
    try:
        record = update_user_record(db, record.id, record.page_number, current_user.id)
        point = get_all_knowledge_points_by_page(db,record.material_id,current_user.id,record.page_number)
        default_point = PageRecordCreate(
            material_id=record.material_id,
            page_number=record.page_number,
            created_at=datetime.now(),
            stone=True
        )  
        if not point:
            # 如果没有记录,插入一个默认值            
            create_knowledge_point(db, default_point, current_user.id)
        # 如果默认记录存在，则更新默认记录
        if len(point) == 1 and point[0].stone:
            update_knowledge_point(db, point[0].id, default_point, current_user.id)
        return record
    except Exception as e:
        app_logger.error(f"更新失败: {e}")
        raise HTTPException(status_code=500, detail="更新失败")

@router.delete("/{record_id}")
def remove_record(record_id: int, db: Session = Depends(get_db), current_user: LearnUser = Depends(get_current_user)):
    return delete_user_record(db, record_id, current_user.id)

@router.get("/{material_id}", response_model=UserRecordResponse)
def get_recored(material_id: int, db: Session = Depends(get_db), current_user: LearnUser = Depends(get_current_user)):
    record = get_user_record(db, current_user.id, material_id)
    if record:
        return record.__dict__
    else:
        record = UserRecordCreate(material_id=material_id, page_number=1,user_id=current_user.id)
        record_response = create_user_record(db, record)
        return record_response.__dict__



